package cn.hdr.train.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 交替打印测试
 * @author: hdr
 * @date: 2020-12-12 15:08
 */
public class PrintTest {

    private int start = 0;
    private boolean flag = true;


    public static void main(String[] args) {
        new PrintTest().print3();
    }


    /**
     * 使用java wait,notify机制进行交替打印
     */
    private void print2(){
        Object lock = new Object();
        final int SUM = 100;

        Runnable runnable = () -> {
            try {
                synchronized (lock){
                    start++;
                    for (int i = start; i <= SUM; i += 2) {
                        lock.notify();
                        System.out.println(Thread.currentThread().getName() + " : " +i);
                        lock.wait();
                    }
                    lock.notify();
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName() + " : " + "exit");
            }
        };

        Thread ta = new Thread(runnable,"A");
        Thread tb = new Thread(runnable,"B");

        ta.start();
        tb.start();
    }

    /**
     * 三个线程交替打印
     */
    private void print3(){
        ReentrantLock lock = new ReentrantLock(true);
        Condition condition = lock.newCondition();
        final int SUM = 100;
        start = 0;

        Runnable runnable = () -> {
            try {
                lock.lock();

                //自旋等待其他线程准备好（执行lock）
                while (flag){
                    if(lock.getQueueLength() == 2){
                        flag = false;
                    }
                }

                for (int i = ++start; i <= SUM; i += 3) {
                    System.out.println(Thread.currentThread().getName() + " : " +i);
                    condition.signal();
                    condition.await();
                }
                condition.signalAll();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " : " + "exit");
            }
        };

        Thread ta = new Thread(runnable,"A");
        Thread tb = new Thread(runnable,"B");
        Thread tc = new Thread(runnable,"C");

        ta.start();
        tb.start();
        tc.start();
    }
}